package com.zl.hyzg.controller;

import com.zl.hyzg.domain.Company;
import com.zl.hyzg.service.CompanyService;
import com.zl.hyzg.util.AliyunOssUtil;
import com.zl.hyzg.util.MD5Utils;
import com.zl.hyzg.vo.CompanyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@Controller
@RequestMapping("/company")
public class CompanyController {
    @Autowired
    private CompanyService companyService;
    @PostMapping("/regist")
    public String addCompany(Company company){
        company.setPassword(MD5Utils.setPwd(company.getPassword()));
        int result = companyService.addCompany(company);
        if(result==1){
            return "success";
        }else{
            return "fail";
        }
    }
@PostMapping("/login")
    public String login(CompanyVo companyVo){
        companyVo.setPassword(MD5Utils.setPwd(companyVo.getPassword()));
        Company company = companyService.login(companyVo);
        if(company ==null ){
            return "fail";
        }else{
            return "success";
        }
    }


    @Autowired
    private AliyunOssUtil ossUtil;

    @GetMapping("/show")
    public String showUpload() {

        return "upload";
    }

    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file, Model model) {
        try {
            String fileName = file.getOriginalFilename();
            if (!"".equals(fileName.trim())) {
                File destFile = new File(fileName);

                //利用输出流,把file里的内容输出destFile中
                FileOutputStream fos = new FileOutputStream(destFile);
                fos.write(file.getBytes());
                fos.close();

                file.transferTo(destFile);

                //TODO:把这个file上传到oss云服务器中!
                String path = ossUtil.upload(destFile);
                System.out.println("path=" + path);

                model.addAttribute("url", path);

                return "success";
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return "success";
    }

}
